package com.jyh.blog.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.blog.dao.ArticleTagDao;
import com.jyh.blog.dao.TagDao;
import com.jyh.blog.dto.TagBackDTO;
import com.jyh.blog.dto.TagDTO;
import com.jyh.blog.entity.ArticleTag;
import com.jyh.blog.entity.Tag;
import com.jyh.blog.exception.MyException;
import com.jyh.blog.service.TagService;
import com.jyh.blog.utils.BeanCopyUtils;
import com.jyh.blog.utils.PageUtils;
import com.jyh.blog.vo.ConditionVO;
import com.jyh.blog.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;

/**
 * (Tag)表服务实现类
 *
 * @author jyh
 * @since 2023-01-14 13:12:44
 */
@Service("tagService")
public class TagServiceImpl extends ServiceImpl<TagDao, Tag> implements TagService {
    @Autowired
    private TagDao tagDao;
    @Autowired
    private ArticleTagDao articleTagDao;

    @Transactional(rollbackFor = Exception.class)
    //添加或修改
    @Override
    public void addOrUpdate(Tag tag) {
        //查询标签是否存在
        Tag existTag = this.getOne(new LambdaQueryWrapper<Tag>().select(Tag::getId).eq(Tag::getName, tag.getName()));
        //需要修改的标签名称存在，并且与当前传入的标签id不一样时，报错
        if (Objects.nonNull(existTag) && !existTag.getId().equals(tag.getId())) {
            throw new MyException("标签名已存在");
        }
        this.saveOrUpdate(tag);
    }

    //（后端）查询所有标签
    @Override
    public PageResult<TagBackDTO> tagListBack(ConditionVO condition) {
        String keywords = condition.getKeywords();
        //查询标签数量
        LambdaQueryWrapper<Tag> lqw = new LambdaQueryWrapper<>();
        lqw.like(!ObjectUtils.isEmpty(keywords), Tag::getName, keywords);
        int count = this.count(lqw);
        if(count==0){
            return new PageResult<>();
        }
        //条件查询
        List<TagBackDTO> records = tagDao.tagListBack(PageUtils.getLimitCurrent(),PageUtils.getSize(),keywords);

        return new PageResult(records,count);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTagById(String id) {
        //有文章使用该标签不能删除
        Integer count = articleTagDao.selectCount(new LambdaQueryWrapper<ArticleTag>().eq(ArticleTag::getTagId, id));
        if(count>0){
            throw new MyException("有文章正在使用，该标签不能被删除");
        }
        tagDao.deleteById(id);
    }

    @Override
    public List<TagDTO> tagList() {
        List<Tag> list = this.list();
        return BeanCopyUtils.copyList(list, TagDTO.class);
    }
}

